!
! astromatch - matching engine
!
!
! Copyright © 2011-2 F.Hroch (hroch@physics.muni.cz)
!
! This file is part of Munipack.
!
! Munipack is free software: you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation, either version 3 of the License, or
! (at your option) any later version.
! 
! Munipack is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU General Public License for more details.
! 
! You should have received a copy of the GNU General Public License
! along with Munipack.  If not, see <http://www.gnu.org/licenses/>.
!

module astromatcher
  
  implicit none
  
  integer, parameter, private :: dbl = selected_real_kind(15)

contains

  subroutine astromatch(nmatch,maxmatch,type,a,d,xx,yy,ac,dc,xc,yc,w,h,id1,id2,like)

    use astrotrafo
    use matcher
    
    integer, intent(in) :: nmatch, maxmatch
    character(len=*), intent(in) :: type
    real(dbl), intent(in) :: ac,dc,xc,yc,w,h
    real(dbl), dimension(:), intent(in) :: a, d, xx, yy
    real(dbl), intent(out) :: like
    integer, dimension(:), allocatable, intent(out) :: id1,id2
    real(dbl), dimension(:), allocatable :: u,v,x,y
    type(TypeProjection) :: t
    real(dbl) :: sc0
    integer :: n

    n = size(xx)
    allocate(x(n),y(n))

    sc0 = (h + w)/2.0_dbl
    x = (xx - xc)/sc0
    y = (yy - yc)/sc0

    t%type = type
    t%acen = ac
    t%dcen = dc
    t%xcen = 0.0_dbl
    t%ycen = 0.0_dbl
    t%scale = 1.0_dbl
    t%pa = 0.0_dbl

!    write(*,*) t%type,t%acen,t%dcen,t%xcen,t%ycen,t%scale,t%pa

    n = size(a)
    allocate(u(n),v(n))

    call trafo(t,a,d,u,v)

    n = min(min(maxmatch,size(u)),min(maxmatch,size(x)))

    call match(u(1:n),v(1:n),x(1:n),y(1:n),nmatch,id1,id2,like)

    if( size(id1) < nmatch .or. size(id2) < nmatch ) like = 0  ! 'Match failed.'

    deallocate(u,v,x,y)

  end subroutine astromatch

end module astromatcher

